<template>
  <div :class="{ 'fullscreen': isFullscreen }">
    <!-- 全屏切换按钮 -->
    <button @click="toggleFullscreen">
      {{ isFullscreen ? '退出全屏' : '进入全屏' }}
    </button>

    <!-- 页面内容 -->
    <div class="content">
      <p>当前全屏状态：{{ isFullscreen ? '全屏中' : '窗口模式' }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';

const isFullscreen = ref(false);

// 全屏状态检测
const checkFullscreen = () => {
  return !!(
    document.fullscreenElement ||
    document.webkitFullscreenElement ||  // Safari
    document.mozFullScreenElement ||     // Firefox
    document.msFullscreenElement         // IE/Edge
  );
};

// 全屏切换
const toggleFullscreen = async () => {
  try {
    if (isFullscreen.value) {
      await exitFullscreen();
    } else {
      await enterFullscreen();
    }
  } catch (error) {
    console.error('全屏操作失败:', error);
  }
};

// 进入全屏
const enterFullscreen = async () => {
  const element = document.documentElement;
  const requestMethods = [
    element.requestFullscreen?.bind(element),
    element.webkitRequestFullscreen?.bind(element),  // Safari
    element.mozRequestFullScreen?.bind(element),     // Firefox
    element.msRequestFullscreen?.bind(element)      // IE/Edge
  ];
  for (const method of requestMethods) {
    if (typeof method === 'function') {
      await method();
      break;
    }
  }
};

// 退出全屏
const exitFullscreen = async () => {
  const exitMethods = [
    document.exitFullscreen?.bind(document),
    document.webkitExitFullscreen?.bind(document),  // Safari
    document.mozCancelFullScreen?.bind(document),   // Firefox
    document.msExitFullscreen?.bind(document)       // IE/Edge
  ];

  for (const method of exitMethods) {
    if (typeof method === 'function') {
      await method();
      break;
    }
  }
};

// 统一处理全屏变化事件
const handleFullscreenChange = () => {
  isFullscreen.value = checkFullscreen();
};

// 事件监听
const setupListeners = () => {
  const events = [
    'fullscreenchange',
    'webkitfullscreenchange',  // Safari
    'mozfullscreenchange',     // Firefox
    'MSFullscreenChange'       // IE/Edge
  ];

  events.forEach(event => {
    document.addEventListener(event, handleFullscreenChange);
  });
};

// 移除监听
const cleanupListeners = () => {
  const events = [
    'fullscreenchange',
    'webkitfullscreenchange',
    'mozfullscreenchange',
    'MSFullscreenChange'
  ];

  events.forEach(event => {
    document.removeEventListener(event, handleFullscreenChange);
  });
};

// 生命周期
onMounted(() => {
  setupListeners();
  isFullscreen.value = checkFullscreen(); // 初始化检测
});

onUnmounted(() => {
  cleanupListeners();
});
</script>

<style scoped>
.fullscreen {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: white;
  z-index: 9999;
}

button {
  padding: 10px 20px;
  margin: 10px;
  cursor: pointer;
}

.content {
  padding: 20px;
}
</style>